<?php

namespace app\admin\controller;

use app\BaseApiController;
use app\admin\model\Role as RoleModel;

class Role extends BaseApiController
{
    protected $middleware = ['token'];

    public function index()
    {
        $pageParams = $this->getPageParams();
        $query = RoleModel::order('id desc');
        $total = $query->count();
        $list = $query->page($pageParams['page'], $pageParams['limit'])->select();
        return $this->pageSuccess($list, $total, $pageParams['page'], $pageParams['limit']);
    }

    public function show($id)
    {
        $record = RoleModel::find($id);
        if (!$record) {
            return $this->error('角色不存在', 404);
        }
        return $this->success($record);
    }

    public function store()
    {
        $params = $this->getParams([
            'name' => 'require|max:64',
            'is_disabled' => 'in:0,1',
        ]);

        $exists = RoleModel::where('name', $params['name'])->find();
        if ($exists) {
            return $this->error('角色名称已存在', 422);
        }

        $params['is_disabled'] = isset($params['is_disabled']) ? (int)$params['is_disabled'] : 0;
        $role = RoleModel::create($params);
        return $this->success($role, '创建成功');
    }

    public function update($id)
    {
        $record = RoleModel::find($id);
        if (!$record) {
            return $this->error('角色不存在', 404);
        }

        $params = $this->getParams([
            'name' => 'max:64',
            'is_disabled' => 'in:0,1',
        ]);

        if (isset($params['name'])) {
            $exists = RoleModel::where('name', $params['name'])->where('id', '<>', $id)->find();
            if ($exists) {
                return $this->error('角色名称已存在', 422);
            }
        }

        if (isset($params['is_disabled'])) {
            $params['is_disabled'] = (int)$params['is_disabled'];
        }

        $record->save($params);
        return $this->success($record, '更新成功');
    }

    public function destroy($id)
    {
        $record = RoleModel::find($id);
        if (!$record) {
            return $this->error('角色不存在', 404);
        }
        $record->delete();
        return $this->success(null, '删除成功');
    }
}


